//
//  LzwAddViewController.m
//  NewHalfsugar
//
//  Created by 刘志武 on 15/12/31.
//  Copyright © 2015年 刘志武. All rights reserved.
//

#import "LzwAddViewController.h"
#import "LzwBaseView.h"
#import "Block.h"
#import "UIImageView+WebCache.h"
#import "LzwAdresstableViewCell.h"
#import "LzwConcernController.h"
#import "LzwAddressDetailVC.h"
#import "LzwAdressWebViewVC.h"
#import "MJRefresh.h"
#import "AFNetworking.h"
#import "LzwBaseImageView.h"
#import "LzwSingleton.h"
#import "LzwbaseTableView.h"
#import "LzwAdressSearchVC.h"
#import "LzwAdressView.h"

@interface LzwAddViewController ()<UITableViewDelegate, UITableViewDataSource, LzwGoumaiDelegata, LzwAdressViewDelegata>

@property (nonatomic, retain) UISegmentedControl * segmentedControl;


@property (nonatomic, retain) LzwAdressView *myAdressView;


@property (nonatomic, retain) LzwbaseTableView *myAddressTableView;

@end

@implementation LzwAddViewController

-(void)dealloc{
    [_myAdressView release];
    [_myAddressTableView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    self.navigationItem.title = @"精选";
    
    
    [self.navigationController.navigationBar setTitleTextAttributes:
     
     
     @{NSFontAttributeName:[UIFont systemFontOfSize:20 * WIDTH],
       
       
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    
    //设置搜索按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"search.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(SearchButtonAction:)];
    
     self.myAddressTableView = [[LzwbaseTableView alloc]initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStylePlain];
    self.myAddressTableView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.myAddressTableView];
    
    
    
    
    
    self.isUpLoading = NO;
    
    // 2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
    
    //实现协议
    self.myAddressTableView.delegate = self;
    self.myAddressTableView.dataSource = self;
    
    //注册cell

    [self.myAddressTableView registerClass:[LzwAdresstableViewCell class] forCellReuseIdentifier:@"cellAdd"];
    
    //初始化数组
    self.arrayAddress = [NSMutableArray array];
    self.arrayAddCell = [NSMutableArray array];
    

    
    //数据解析
    NSString *str = @"http://open3.bantangapp.com/community/post/editorRec";
    
    NSDictionary *dicDD = @{@"app_installtime":@"1451365479.933367", @"app_versions":@"5.1.1", @"channel_name":@"appStore", @"client_id":@"bt_app_ios", @"client_secret":@"9c1e6634ce1c5098e056628cd66a17a5", @"device_token":@"c02c60075e7bab110fbdf27e15de3cb61e97360c4ea3545fd8a5936e46c28ccb", @"last_time":@"1451366546", @"os_versions":@"9.1", @"page":@"0", @"pagesize":@"10", @"screensize":@"640", @"track_device_info":@"iPhone5%2C3", @"track_deviceid":@"A80585E3-D6AD-4A53-BE1C-5963901C96E5",@"v":@"9"};
    

    [Block creatingDataTask:str parameters:dicDD Cookie:nil User_Agent:nil successAFNBlock:^(id resuposeObject) {
        
        NSMutableDictionary *dic = [resuposeObject objectForKey:@"data"];
        
        NSMutableArray *array = [dic objectForKey:@"element"];
        
        for (NSMutableDictionary *diction in array) {
            
            LzwAdressModle *modleAdd = [[LzwAdressModle alloc]init];
            
            [modleAdd setValuesForKeysWithDictionary:diction];
            
            [self.arrayAddress addObject:modleAdd];
            
            [[LzwSingleton shareDataBase] insertLzwAdressHeadIntoTable:modleAdd];
            
        }
        
        self.myAdressView.array = self.arrayAddress;

        NSMutableArray *arrayBo = [dic objectForKey:@"list"];
        
        for (NSMutableDictionary *diction in arrayBo) {
            
            self.modleSmall = [[LzwModleSmall alloc]init];
            
            [self.modleSmall setValuesForKeysWithDictionary:diction];
            
            [self.arrayAddCell addObject:self.modleSmall];
            
            [[LzwSingleton shareDataBase] insertLzwNewAdressFootIntoTable:self.modleSmall];
            
            NSLog(@"ssssss = %@", self.modleSmall.content);
        }
        
        NSString *stringggg = self.modleSmall.content;
        
        NSLog(@"aaaaaaaa = %@", stringggg);
        
        [self.myAddressTableView reloadData];

        
        
    }];
    
    
    
    
    //设置头部
    self.myAddressTableView.tableHeaderView = [self creatAddressHeader];

  
 
    
}

//设置头部区域内容
-(LzwBaseView *)creatAddressHeader{
    

    self.myAdressView = [[LzwAdressView alloc]initWithFrame:CGRectMake(0, 0, 375 * WIDTH, 220 * WIDTH)];
    self.myAdressView.myAdressViewDelegata = self;

       return self.myAdressView;
}

-(void)pushDtailPage:(NSInteger)xiabiao{
    
    NSLog(@"........%ld", xiabiao);
    
    if (xiabiao == 20001) {
        
        LzwAdressWebViewVC *addressWeb = [[LzwAdressWebViewVC alloc]init];
        
        addressWeb.modleWeb = [self.arrayAddress objectAtIndex:0];
        
        [self.navigationController pushViewController:addressWeb animated:YES];
        
    }else if (xiabiao == 20002){
        LzwAdressWebViewVC *addressWeb = [[LzwAdressWebViewVC alloc]init];
        
        
        addressWeb.modleWeb = [self.arrayAddress objectAtIndex:1];
        [self.navigationController pushViewController:addressWeb animated:YES];
        
    }else if (xiabiao == 20003){
        LzwAdressWebViewVC *addressWeb = [[LzwAdressWebViewVC alloc]init];
        
        
        addressWeb.modleWeb = [self.arrayAddress objectAtIndex:2];
        [self.navigationController pushViewController:addressWeb animated:YES];
        
    }else{
        LzwAdressWebViewVC *addressWeb = [[LzwAdressWebViewVC alloc]init];
        
        
        addressWeb.modleWeb = [self.arrayAddress objectAtIndex:3];
        [self.navigationController pushViewController:addressWeb animated:YES];
        
        
    }
    
    
    
}






//创建row
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.arrayAddCell.count;
}
//设置cell的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LzwAdresstableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellAdd"];
    
    cell.myAddreeshopDele = self;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.modleSma = [self.arrayAddCell objectAtIndex:indexPath.row];
    
    
    return cell;
}
//设置cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LzwAddressDetailVC *addVC = [[LzwAddressDetailVC alloc]init];
    
    addVC.modleDetailAdd = [self.arrayAddCell objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:addVC animated:YES];
}


//设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 480;
}




//实现购物协议方法 push到webView
-(void)pushShoppingPage:(NSString *)item_id{
    
    LzwConcernController *coVC = [[LzwConcernController alloc]init];
    
    
    coVC.WebViewId = item_id;
    [self.navigationController pushViewController:coVC animated:YES];
}

//关注的协议方法
-(void)AttentionButtion:(LzwModleSmall *)modleS{
    
    
    
    //逻辑:判断数据库是否已经收藏,如果收藏过就提示该活动应经收藏,没有就插入
    
  
    
    NSMutableArray *array = [[LzwSingleton shareDataBase] selectAttentionTable];
        //判断是否已经收藏,得先把数据库里面的值取出来,遍历放入Modle对象里,在对象里面把content取出来,在放入数组中,此时这个数组放的全是content,然后在判断这个数组是否包含一样的content;
        
  NSMutableArray *contentArray = [NSMutableArray array];
        for (LzwModleSmall *modles in array) {
            [contentArray addObject:modles.content];
            
        }
    
        if ([contentArray containsObject:modleS.content]) {
            
            
            
            UIAlertController *aler = [UIAlertController alertControllerWithTitle:@"提示" message:@"该物品已经被关注!!!" preferredStyle:UIAlertControllerStyleAlert];
            
            [self presentViewController:aler animated:YES completion:^{
                [self dismissViewControllerAnimated:YES completion:^{
                    
                    
                }];
                
            }];
            return;
        }else{
        
            [[LzwSingleton shareDataBase] insertAttentionIntoTable:modleS];
  
        UIAlertController *con = [UIAlertController alertControllerWithTitle:@"提示" message:@"关注成功" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:con animated:YES completion:^{
            
            [self dismissViewControllerAnimated:YES completion:^{
                
                
            }];
            
        }];
        
        }
}

#pragma mark --下拉刷新
- (void)addHeader
{
    //    __unsafe_unretained typeof(self) vc = self;
    
    __block LzwAddViewController *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myAddressTableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        [self.arrayAddress removeAllObjects];
        vc.nextPage = 1;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
        
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myAddressTableView headerBeginRefreshing];
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    //    __unsafe_unretained typeof(self) vc = self;
    __block LzwAddViewController *vc = self;
    
    // 添加上拉刷新尾部控件
    [self.myAddressTableView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        
        vc.nextPage ++;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
        
    }];
}





#pragma mark --使用AFN进行数据请求
-(void)GetPersonList:(NSInteger)nextCursor
{
    
   
    
    
    NSString *string = @"http://open3.bantangapp.com/community/post/editorRec";
    
    NSDictionary *dicA = @{@"app_installtime":@"1451365479.933367", @"app_versions":@"5.1.1", @"channel_name":@"appStore", @"client_id":@"bt_app_ios", @"client_secret":@"9c1e6634ce1c5098e056628cd66a17a5", @"device_token":@"c02c60075e7bab110fbdf27e15de3cb61e97360c4ea3545fd8a5936e46c28ccb", @"oauth_token":@"a41d3848f43102aa7759c27ba2c0fe8f", @"os_versions":@"9.1", @"page":[NSString stringWithFormat:@"%ld", nextCursor], @"pagesize":@"10", @"screensize":@"640"};
    
    
    if (self.isUpLoading == NO) {
        //说明是下拉，就要清空数组中的数据
        [self.arrayAddCell removeAllObjects];
    }
    
    //=&=&=&=&=&=&last_id=100360&last_time=1452001409&=&    ///=&=&=&=&track_device_info=iPhone5%2C3&track_deviceid=A80585E3-D6AD-4A53-BE1C-5963901C96E5&track_user_id=1746436&v=9
    
    [Block creatingDataTask:string parameters:dicA Cookie:nil User_Agent:nil successAFNBlock:^(id resuposeObject) {
        
        NSMutableDictionary *dic = [resuposeObject objectForKey:@"data"];

        NSMutableArray *arrayBo = [dic objectForKey:@"list"];
        
        for (NSMutableDictionary *diction in arrayBo) {
            
            LzwModleSmall *modleSmall = [[LzwModleSmall alloc]init];
            
            [modleSmall setValuesForKeysWithDictionary:diction];
            
            [self.arrayAddCell addObject:modleSmall];
            
            
        }
        

        
    }];
        [self.myAddressTableView footerEndRefreshing];
        [self.myAddressTableView headerEndRefreshing];
        [self.myAddressTableView reloadData];
        
        
}

//点击搜索按钮触发事件
- (void)SearchButtonAction:(UIBarButtonItem *)serch{
    
    LzwAdressSearchVC *searchVC = [[LzwAdressSearchVC alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
